package com.shwread.android.ui.widget.staggeredgrid;


import android.content.Context;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.shwread.android.ui.widget.staggeredgrid.util.DynamicHeightImageView;

import java.util.ArrayList;
import java.util.Random;


public class SampleAdapter extends BaseAdapter {

    private static final String TAG = "SampleAdapter";
    private ArrayList<String[]> mData;
    static class ViewHolder {
    	DynamicHeightImageView img;
        TextView txt;
    }

    private final LayoutInflater mLayoutInflater;
    private final Random mRandom;

    private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();

    public SampleAdapter(final Context context, ArrayList<String[]> mData) {
    	this.mData = mData;
        mLayoutInflater = LayoutInflater.from(context);
        mRandom = new Random();
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        ViewHolder vh;
        if (convertView == null) {
        	//TODO
//            convertView = mLayoutInflater.inflate(R.layout.atlas_item, parent, false);
            vh = new ViewHolder();
//            vh.txt = (TextView) convertView.findViewById(R.id.atlas_item_txt);
//            vh.img = (DynamicHeightImageView) convertView.findViewById(R.id.atlas_item_img);

            convertView.setTag(vh);
        }
        else {
            vh = (ViewHolder) convertView.getTag();
        }

        double positionHeight = getPositionRatio(position);

        Log.d(TAG, "getView position:" + position + " h:" + positionHeight);

        vh.img.setHeightRatio(positionHeight);
        vh.txt.setText(mData.get(position)[0]);

        return convertView;
    }

    private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);
        // if not yet done generate and stash the columns height
        // in our real world scenario this will be determined by
        // some match based on the known height and width of the image
        // and maybe a helpful way to get the column height!
        if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
            Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
        }
        return ratio;
    }

    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width
    }

	@Override
    public int getCount() {
	    return mData.size();
    }

	@Override
    public Object getItem(int arg0) {
	    return null;
    }

	@Override
    public long getItemId(int arg0) {
	    return arg0;
    }
}